package cs235.xml;

import java.io.IOException;
import java.io.InputStream;

public class XMLParser implements Parser {

    public XMLParser() {}

    @Override
    public Document parse(InputStream input) throws IOException, XMLException {
          
        
        TokenizerImpl tokenReader = new TokenizerImpl(input);
        XMLDocument document = new XMLDocument();
        int next = tokenReader.nextToken();
        while (next != Tokenizer.EOF){
            if (next == Tokenizer.START_TAG){
//                createElement(tokenReader, document);
                document.appendChild(createElement(tokenReader, document));
            } else if (next == Tokenizer.TEXT){
//                createText(tokenReader, document);
                document.appendChild(createText(tokenReader, document));
            } else if (next == Tokenizer.END_TAG){
                throw new XMLException("Had and end tag with no starting one");
            }
            next = tokenReader.nextToken();
        }

        return document;
    }

    public XMLElement createElement(TokenizerImpl reader, XMLNode node) throws IOException,
            XMLException {
        XMLElement element = new XMLElement(node);
        element.setTagName(reader.getTagName());
        int attrcount = reader.getAttributeCount();
        for (int i = 0; i < attrcount; i++) {
            element.setAttribute(reader.getAttributeName(i),
                    reader.getAttributeValue(i));
        }
        int nextToken = reader.nextToken();
        while (nextToken != Tokenizer.END_TAG) {
            if (nextToken == Tokenizer.START_TAG){
//                createElement(reader, element);
                element.appendChild(createElement(reader, element));
            } else if (nextToken == Tokenizer.TEXT){
//                createText(reader, element);
                element.appendChild(createText(reader, element));
            } else if (nextToken == Tokenizer.EOF){
                throw new XMLException("Unexpected end of file");
            }
            nextToken = reader.nextToken();
            
        }
        String closeTag = reader.getTagName();
        if (!closeTag.equals(element.getTagName())) {
            throw new XMLException("Tags are unbalanced. OpenTag:\""
                    + element.getTagName() + "\" CloseTag:\"" + closeTag + "\"");
        }
        return element;
    }

    public XMLText createText(TokenizerImpl reader, XMLNode node) {
        XMLText text = new XMLText(node);
        text.setData(reader.getText());
        return text;
    }

}
